<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/12
 */

namespace app\wap\controller;


use app\wap\model\store\StoreCombination;
use app\admin\model\system\SystemGroup;
use app\admin\model\system\SystemGroupData;
use app\wap\model\store\StoreCategory;
use app\wap\model\store\StoreCouponIssue;
use app\wap\model\store\StoreProduct;
use app\wap\model\wap\ArticleCategory;
use app\wap\model\store\StoreProductReply;
use service\JsonService;
use service\UtilService;
use think\Cache;
use service\GroupDataService;

class PublicApi
{
    public function get_cid_article($cid = 0,$first = 0,$limit = 8)
    {
        $list = ArticleCategory::cidByArticleList($cid,$first,$limit,'id,title,image_input,visit,add_time,synopsis,url')?:[];

        foreach ($list as &$article){
            $article['add_time'] = date('Y-m-d H:i',$article['add_time']);
        }
        return JsonService::successful('ok',$list);
    }

    public function get_video_list($key = '', $first = 0,$limit = 8)
    {
        $gid = SystemGroup::where('config_name',$key)->value('id');
        if(!$gid){
            $list = [];
        }else{
            $video = SystemGroupData::where('gid',$gid)->where('status',1)->order('sort DESC,add_time DESC')->limit($first,$limit)->select();
            $list = SystemGroupData::tidyList($video);
        }
        return JsonService::successful('ok',$list);
    }

    public function get_issue_coupon_list($limit = 2)
    {
        $list = StoreCouponIssue::validWhere('A')->join('__STORE_COUPON__ B','A.cid = B.id')
            ->field('A.*,B.coupon_price,B.use_min_price')->order('id DESC')->limit($limit)->select()->toArray();
        return JsonService::successful($list);
    }

    public function get_category_product_list($limit = 4, $callback = '')
    {
        $cateInfo = StoreCategory::where('is_show',1)->where('pid',0)->field('id,cate_name,pic')
            ->order('sort DESC')->select()->toArray();
        $result = [];
        $StoreProductModel = new StoreProduct;
        foreach ($cateInfo as $k=>$cate){
            $cate['product'] = $StoreProductModel::alias('A')->where('A.is_del',0)->where('A.is_show',1)
                ->where('A.mer_id',0)->where('B.pid',$cate['id'])
                ->join('__STORE_CATEGORY__ B','B.id = A.cate_id')
                ->order('A.is_benefit DESC,A.sort DESC,A.add_time DESC')
                ->limit($limit)->field('A.id,A.image,A.store_name,A.sales,A.price,A.unit_name')->select()->toArray();
            if(count($cate['product']))
                $result[] = $cate;
        }
        return JsonService::successful('ok', $result, 200, $callback);
    }

    public function get_product_list($keyword = '', $id, $cId = 0,$sId = 0,$priceOrder = '', $salesOrder = '', $news = 0, $page_num = 1, $page_size = 20, $callback = ''){
        if(!empty($keyword)){
            $encodedData = str_replace(' ','+',$keyword);
            $keyword = base64_decode(htmlspecialchars($encodedData));
        }
        if($id>0&&$cId == 0){
            $cId = $id;
        }
        $model = StoreProduct::validWhere();
        if($cId && $sId){
            $model->where('cate_id',$sId);
        }elseif($cId){
            $sids = StoreCategory::pidBySidList($cId)?:[];
            if(is_array($cId)){
                $sids = array_merge($cId, $sids);
            }else{
               $sids[] = $cId; 
            }
            $model->where('cate_id','IN',$sids);
        }
        if(!empty($keyword)) $model->where('keyword|store_name','LIKE',"%$keyword%");
        if($news) $model->where('is_new',1);
        $baseOrder = '';
        if($priceOrder) $baseOrder = $priceOrder == 'desc' ? 'price DESC' : 'price ASC';
//        if($salesOrder) $baseOrder = $salesOrder == 'desc' ? 'sales DESC' : 'sales ASC';
        if($salesOrder) $baseOrder = $salesOrder == 'desc' ? 'ficti DESC' : 'ficti ASC';
        if($baseOrder) $baseOrder .= ', ';
        $model->order($baseOrder.'sort DESC, add_time DESC');
        $list = $model->limit(($page_num-1)*$page_size,$page_size)->field('id,store_name,image,sales,ficti,price,stock')->select()->toArray();

        foreach($list as $k=>$v){
            $list[$k]['comment_count'] = 0;
            $list[$k]['fav_comment_rate'] = 100;
        }

        return JsonService::successful('ok', ['list'=>$list], 200, $callback);
    }

    public function get_cate_list($cId = [1,2,3,4],$sId = 0,$priceOrder = '', $salesOrder = '', $news = 0, $first = 0, $limit = 8, $callback = ''){
        $cates = StoreCategory::cateBySidList($cId)?:[];

        $parentCates = StoreCategory::catesByCid($cId);

        $cates_map = [];

        foreach($cates as $k=>$v){
            $cates_map[$v['pid']][] = $v;
        }

        foreach($parentCates as $k=>$v){
            $parentCates[$k]['sub_cate_list'] = $cates_map[$v['id']];
        }

       return JsonService::successful('ok', ['list'=>$parentCates], 200, $callback);
    }

    private function ary2map($ary, $key_field){
        $ret_ary = array();
        foreach ($ary as $v) {
            if ($v[$key_field] || isset($v[$key_field])) {
                $ret_ary[$v[$key_field]][] = $v;
            }
        }
        return $ret_ary;
    }

    public function get_best_product_list($first = 0,$limit = 8)
    {
        $list = StoreProduct::validWhere()->where('mer_id',0)->order('is_best DESC,sort DESC,add_time DESC')
            ->limit($first,$limit)->field('id,image,store_name,sales,price,unit_name')->select()->toArray();
        foreach($list as $k=>$v){
            $list[$k]['comment_count'] = 0;
            $list[$k]['fav_comment_rate'] = 100;
        }
        return JsonService::successful($list);
    }

    public function get_best_product($page_num = 1,$page_size = 20, $callback = '')
    {
        $list = StoreProduct::validWhere()->where('mer_id',0)->order('is_best DESC,sort DESC,add_time DESC')
            ->limit( ($page_num-1)*$page_size, $page_size)->field('id,image,store_name,sales,price,unit_name')->select()->toArray();

        return JsonService::successful('ok', ['list'=>$list, 'page_num'=>$page_num, 'page_size'=>$page_size], 200, $callback);
    }

    public function get_banner($callback = ''){
        $banner = GroupDataService::getData('store_home_banner');
        return JsonService::successful('ok', $banner, 200, $callback);
    }

    public function wechat_media_id_by_image($mediaIds = '')
    {
        if(!$mediaIds) return JsonService::fail('参数错误');
        $mediaIds = explode(',',$mediaIds);
        $temporary = \service\WechatService::materialTemporaryService();
        $pathList = [];
        foreach ($mediaIds as $mediaId){
            if(!$mediaId) continue;
            try{
                $content = $temporary->getStream($mediaId);
            }catch (\Exception $e){
                continue;
            }
            $name = substr(md5($mediaId),12,20).'.jpg';
            $path = '.'.DS.'public'.DS.'uploads'.DS.'wechat'.DS.'media'.DS.$name;
            $res = file_put_contents($path,$content);
            if($res) $pathList[] = UtilService::pathToUrl($path);
        }
        return JsonService::successful($pathList);
    }


    public function get_pink_host($limit = 0){
        $list = StoreCombination::getCombinationHost($limit);
        if($list) return JsonService::successful($list);
        else return JsonService::successful([]);
    }

    public function get_comment($id, $callback = ''){
        if(!$id || !is_numeric($id)) return JsonService::fail('fail', ['msg'=>'参数错误'], 200, $callback);
        $comment_list = StoreProductReply::getRecProductReply($id);
        $comment_count = StoreProductReply::productValidWhere()->where('product_id',$id)->count();
        return JsonService::successful('ok', ['info'=>$comment_list, 'comment_count'=>$comment_count], 200, $callback);
    }

    public function get_comment_list($id, $page_num = 1, $page_size = 20, $callback = ''){
        if(!$id || !is_numeric($id)) return JsonService::fail('fail', ['msg'=>'参数错误'], 200, $callback);
        $comment_list = StoreProductReply::getProductReplyList($id, 'All', ($page_num-1)*$page_size, $page_size);
        return JsonService::successful('ok', ['list'=>$comment_list, 'page_num'=>$page_num, 'page_size'=>$page_size], 200, $callback);
    }

}